//
//  LZTextViewExtension.swift
//  halikaPeso
//
//  Created by L-zh on 2024/12/16.
//

import SnapKit
 class LZTextView: UITextView {
   
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
        addObserver(self, forKeyPath: "text", options: .new, context: nil)
    }
    /// textView 的值改变
    @objc func textDidChanged() {

        placeHolderView.isHidden = !StringIsEmpty(value: self.text)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        placeHolderView.isHidden = !StringIsEmpty(value: self.text)
    }
    
    /// 占位字符
    var placeHolder: String? {
        didSet{
            if let _ = placeHolder {
                placeholderView()
                placeHolderView.text = placeHolder
            }
        }
    }
    
    /// 占位字符颜色
    var placeholderColor: UIColor? {
        didSet{
            if let _ = placeHolder {
                placeHolderView.textColor = placeholderColor
            }
        }
    }
    
    /// 占位字符大小
    var placeholderFontSize: CGFloat? {
        didSet{
            if let _ = placeHolder {
                placeHolderView.font = UIFont.systemFont(ofSize: placeholderFontSize ?? 14)
            }
        }
    }
    /// 占位字符视图
    private lazy var placeHolderView:UILabel = {
        let lable = UILabel()
        lable.textColor = UIColor.lightGray
        lable.font = APPFont(f: 26)
        return lable
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 设置页面
extension LZTextView {
    
    func setUpUI() {
        // 监听 textView 的值的变化
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(textDidChanged),
                                               name: UITextView.textDidChangeNotification,
                                               object: nil)
        placeholderView()
    }
    
    /// 创建占位视图
    func placeholderView() {
         addSubview(placeHolderView)
        placeHolderView.snp.makeConstraints { (make) in
            make.left.top.equalTo(self).offset(5)
        }
    }
}

